package thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

public class CASDemo {
    public static void main(String[] args) {
        AtomicStampedReference<Integer> integerAtomicStampedReference = new AtomicStampedReference<Integer>(1,1);
        new Thread(()->{
            int stamp = integerAtomicStampedReference.getStamp();
            System.out.println("a1   " + stamp);

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            
            integerAtomicStampedReference.compareAndSet(1,2,
                    integerAtomicStampedReference.getStamp(),integerAtomicStampedReference.getStamp() + 1);

            System.out.println("a2  " + integerAtomicStampedReference.getStamp());

            System.out.println(integerAtomicStampedReference.compareAndSet(2,1,
                    integerAtomicStampedReference.getStamp(),integerAtomicStampedReference.getStamp() + 1));

            System.out.println("a3  " + integerAtomicStampedReference.getStamp());
        },"A").start();


        new Thread(()->{
            int stamp = integerAtomicStampedReference.getStamp();
            System.out.println("b1   " + stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            integerAtomicStampedReference.compareAndSet(1,2,
                    integerAtomicStampedReference.getStamp(),integerAtomicStampedReference.getStamp() + 1);

            System.out.println("b2  " + integerAtomicStampedReference.getStamp());


        },"B").start();
    }
}
